package com.sample.controller;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ResourceLoader;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.sample.entity.UserInfo;
import com.sample.entity.LoginInfo;
import com.sample.entity.PurchaseDetail;
import com.sample.entity.PurchaseInfoVO;
import com.sample.entity.PurchaseInfoVO2;
import com.sample.util.BeanFactory;
import com.sample.util.ConnectionUtils;

import cn.hutool.json.JSONUtil;
import net.sf.jasperreports.engine.JRDataSource;
import net.sf.jasperreports.engine.JREmptyDataSource;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import net.sf.jasperreports.engine.design.JRDesignBand;
import net.sf.jasperreports.engine.design.JRDesignElementGroup;
import net.sf.jasperreports.engine.design.JRDesignExpression;
import net.sf.jasperreports.engine.design.JRDesignField;
import net.sf.jasperreports.engine.design.JRDesignStaticText;
import net.sf.jasperreports.engine.design.JRDesignTextField;
import net.sf.jasperreports.engine.design.JasperDesign;
import net.sf.jasperreports.engine.util.JRLoader;
import net.sf.jasperreports.engine.xml.JRXmlLoader;

@RestController
@RequestMapping("/samplereport")
public class SampleReportController {
  
	@Autowired
	private ResourceLoader resourceLoader;
	
	@GetMapping("/reportJdbc")
	public void reportJdbc(HttpServletRequest req,HttpServletResponse resp) throws IOException {
		   
		  resp.setContentType("application/pdf;charset=utf-8");
		  resp.setDateHeader("Expire", 0);
		  OutputStream os = resp.getOutputStream();
		  try {
			//装载
			JasperReport jasperReprot = (JasperReport) JRLoader.loadObject(resourceLoader.getResource("classpath:/jasper/sample1.jasper").getInputStream());
		
			//填充
			JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReprot, null, ConnectionUtils.getConnection());
			
			//展现
			JasperExportManager.exportReportToPdfStream(jasperPrint, os);
			
		  } catch (JRException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		  
	}
	//http://localhost:8080/samplereport/reportJavabean
	@GetMapping("/reportJavabean")
	public void reportJavabean(HttpServletRequest req,HttpServletResponse resp) throws IOException {
		   
		  resp.setContentType("application/pdf;charset=utf-8");
		  resp.setDateHeader("Expire", 0);
		  OutputStream os = resp.getOutputStream();
		  try {
			  
			  //装载报表
	    	   JasperReport jasperReport = (JasperReport)JRLoader.loadObject(resourceLoader.getResource("classpath:/jasper/sample2.jasper").getInputStream()); 
	    	  //创建Bean并填充数据源
	    	   List list = new ArrayList();
	    	   UserInfo info = new UserInfo();
	    	   info.setLoginId("xiaoba");
	    	   info.setLoginName("小八");
	    	   info.setLocation("北街");
	    	   info.setSex("1");
	    	   info.setAddress("北路1号");
	    	   info.setBirthday("20190909");
	    	   info.setCreateTime(new Date());
	    	   list.add(info);
	    	   UserInfo info1 = new UserInfo();
	    	   info1.setLoginId("xiaozhang");
	    	   info1.setLoginName("小张");
	    	   info1.setLocation("北街");
	    	   info1.setSex("1");
	    	   info1.setAddress("北路2号");
	    	   info1.setBirthday("20190929");
	    	   info1.setCreateTime(new Date());
	    	   list.add(info1);
	    	   
	    	   JRBeanCollectionDataSource ds = new JRBeanCollectionDataSource(list);
	    	   JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, null, ds);
	    	   //展现报表
	           JasperExportManager.exportReportToPdfStream(jasperPrint,os); 
			
		  } catch (JRException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		  
	}
	//http://localhost:8080/samplereport/reportbean
	@GetMapping(value = "/reportbean") 
	public void reportbean(HttpServletRequest request, HttpServletResponse response) throws IOException {
		  try {   
			  String reportName ="sampleMain6.jasper";
			   response.setContentType("application/pdf; charset=utf-8");  
               response.setDateHeader("Expires", 0);  
			   OutputStream os = response.getOutputStream(); 
	    	   JasperReport jasperReport = (JasperReport)JRLoader.loadObject(resourceLoader.getResource("classpath:/jasper/sample6/"+reportName).getInputStream());
	    	   String subPath = resourceLoader.getResource("classpath:/jasper/sample6/").getURL().toString(); 
	    	    
	    	   JRBeanCollectionDataSource detailDs = new JRBeanCollectionDataSource(BeanFactory.getOrderList());
	    	   JRBeanCollectionDataSource detailDs1 = new JRBeanCollectionDataSource(BeanFactory.getAccountInfoList());
	    	   HashMap<String, Object> hashMap = new HashMap<>(); 
	    	   hashMap.put("subPath", subPath);
	    	   hashMap.put("subdata1", detailDs);
	    	   hashMap.put("subdata2", detailDs1);
	    	   
	    	   JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, hashMap,new JREmptyDataSource());
	    	      
	           JasperExportManager.exportReportToPdfStream(jasperPrint,os);  
	} catch (Exception e) {
		 e.printStackTrace();
	}
	}
	//http://localhost:8080/samplereport/reportbean2
	@GetMapping(value = "/reportbean2") 
	public void reportgroup(HttpServletRequest request, HttpServletResponse response) throws IOException {
		  try {   
			  String reportName ="sample7.jasper";
			   response.setContentType("application/pdf; charset=utf-8");  
               response.setDateHeader("Expires", 0);  
			   OutputStream os = response.getOutputStream(); 
	    	   JasperReport jasperReport = (JasperReport)JRLoader.loadObject(resourceLoader.getResource("classpath:/jasper/sample7/"+reportName).getInputStream());
	    	   String subPath = resourceLoader.getResource("classpath:/jasper/sample7/").getURL().toString(); 
	    	    
	    	   JRBeanCollectionDataSource detailDs = new JRBeanCollectionDataSource(BeanFactory.getPurchaseInfo()); 
	    	   HashMap<String, Object> hashMap = new HashMap<>(); 
	    	   hashMap.put("subPath", subPath); 
	    	   
	    	   
	    	   JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, hashMap,detailDs);
	    	      
	           JasperExportManager.exportReportToPdfStream(jasperPrint,os);  
		} catch (Exception e) {
			 e.printStackTrace();
		}
	}  
	//http://localhost:8080/samplereport/reportjson1
	@GetMapping(value = "/reportjson1") 
	public void reportjson1(HttpServletRequest request, HttpServletResponse response) throws IOException {
		  try {  
			  String reportName ="sample3.jasper";
			   response.setContentType("application/pdf; charset=utf-8");  
               response.setDateHeader("Expires", 0);  
			   OutputStream os = response.getOutputStream(); 
			   //装载报表
	    	   JasperReport jasperReport = (JasperReport)JRLoader.loadObject(resourceLoader.getResource("classpath:/jasper/"+reportName).getInputStream());
				 
	    	   HashMap<String, Object> hashMap = new HashMap<>(); 
	    	   //构建json 数据源并填充报表
	    	   String json = buildJson1();
	    	   System.out.println(json);
	    	   InputStream inputStream = new ByteArrayInputStream(json.getBytes("UTF-8")); 
		       hashMap.put("JSON_INPUT_STREAM", inputStream); 		       //填充报表数据源数据流 
	    	   JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, hashMap);
	    	     //预览
	           JasperExportManager.exportReportToPdfStream(jasperPrint,os); 
	} catch (Exception e) {
		 e.printStackTrace();
	}
	}
	
	private String buildJson1() {
		 List list = new ArrayList();
  	   UserInfo info = new UserInfo();
  	   info.setLoginId("xiaoba");
  	   info.setLoginName("小八");
  	   info.setLocation("北街");
  	   info.setSex("1");
  	   info.setAddress("北路1号");
  	   info.setBirthday("20190909");
  	   info.setCreateTime(new Date());
  	   list.add(info);
  	   UserInfo info1 = new UserInfo();
  	   info1.setLoginId("xiaozhang");
  	   info1.setLoginName("小张");
  	   info1.setLocation("北街");
  	   info1.setSex("1");
  	   info1.setAddress("北路2号");
  	   info1.setBirthday("20190919");
  	   info1.setCreateTime(new Date());
  	   list.add(info1);
  	   String json= JSONUtil.toJsonStr(list); 
  	   return json;
	}
	//http://localhost:8080/samplereport/reportjson2
	@GetMapping(value = "/reportjson2") 
	public void reportjson2(HttpServletRequest request, HttpServletResponse response) throws IOException {
		  try {  
			  String reportName ="sample4.jasper";
			   response.setContentType("application/pdf; charset=utf-8");  
               response.setDateHeader("Expires", 0);  
			   OutputStream os = response.getOutputStream(); 
			    //装载主报表
	    	   JasperReport jasperReport = (JasperReport)JRLoader.loadObject(resourceLoader.getResource("classpath:/jasper/"+reportName).getInputStream());
	    	    //报表参数
	    	   String subPath = resourceLoader.getResource("classpath:/jasper/").getURL().toString(); 
	    	   
	    	   HashMap<String, Object> hashMap = new HashMap<>(); 
	    	   hashMap.put("subPath", subPath);
	    	   String json = buildJson2();
	    	   System.out.println(json);
	    	   InputStream inputStream = new ByteArrayInputStream(json.getBytes("UTF-8")); 
		       hashMap.put("JSON_INPUT_STREAM", inputStream); //填充报表数据源数据流 
		       //填充报表数据
	    	   JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, hashMap);
	    	   //展现
	           JasperExportManager.exportReportToPdfStream(jasperPrint,os);  
	} catch (Exception e) {
		 e.printStackTrace();
	}
	}
	private String buildJson2() {
		PurchaseInfoVO vo = new PurchaseInfoVO();
 	   vo.setLoginId("lisi");
 	   vo.setLoginName("李四") ;
 	   vo.setLocation("北京");
 	   vo.setAddress("长安大街1号");
 	   vo.setPhone("13344444444");
 	   
 	   List<PurchaseDetail> orderList= new ArrayList<PurchaseDetail>();
 	   PurchaseDetail order = new PurchaseDetail();
 	   order.setOrderId("20200101"); 
 	   order.setProductName("笔记本");
 	   order.setCount(2);
 	   order.setPrice(new BigDecimal("22.2"));
 	   order.setPurchaseTime(new Date()); 
 	   orderList.add(order);
 	   
 	   PurchaseDetail order1 = new PurchaseDetail();
 	   order1.setOrderId("20200102"); 
 	   order1.setProductName("硬盘");
 	   order1.setCount(1);
 	   order1.setPrice(new BigDecimal("222.02"));
 	   order1.setPurchaseTime(new Date()); 
 	   orderList.add(order1); 
 	   
 	   vo.setOrderList(orderList);
 	   return  JSONUtil.toJsonStr(vo); 
	}
	//http://localhost:8080/samplereport/reportjson3
	@GetMapping(value = "/reportjson3") 
	public void reportjson3(HttpServletRequest request, HttpServletResponse response) throws IOException {
		  try {  
			  String json = buildJson3();
			  System.out.println(json);
			  String reportName ="sampleMain5.jasper";
			   response.setContentType("application/pdf; charset=utf-8");  
               response.setDateHeader("Expires", 0);  
			   OutputStream os = response.getOutputStream(); 
	    	   JasperReport jasperReport = (JasperReport)JRLoader.loadObject(resourceLoader.getResource("classpath:/jasper/sample5/"+reportName).getInputStream());
	    	   String subPath = resourceLoader.getResource("classpath:/jasper/sample5/").getURL().toString(); 
	    	   
	    	   HashMap<String, Object> hashMap = new HashMap<>(); 
	    	   hashMap.put("subPath", subPath);
	    	  
	    	  
	    	   InputStream inputStream = new ByteArrayInputStream(json.getBytes("UTF-8")); 
		       hashMap.put("JSON_INPUT_STREAM", inputStream); //填充报表数据源数据流 
	    	   JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, hashMap);
	    	      
	           JasperExportManager.exportReportToPdfStream(jasperPrint,os);  
	} catch (Exception e) {
		 e.printStackTrace();
	}
	}
	
	private String buildJson3() {
	   PurchaseInfoVO2 purchaseInfo = new PurchaseInfoVO2();
	   LoginInfo vo = new LoginInfo();
 	   vo.setLoginId("lisi");
 	   vo.setLoginName("李四") ;
 	   vo.setLocation("北京");
 	   vo.setAddress("长安大街1号");
 	   vo.setPhone("13344444444");
 	   
 	   List<PurchaseDetail> orderList= new ArrayList<PurchaseDetail>();
 	   PurchaseDetail order = new PurchaseDetail();
 	   order.setOrderId("20200101"); 
 	   order.setProductName("笔记本");
 	   order.setCount(2);
 	   order.setPrice(new BigDecimal("22.2"));
 	   order.setPurchaseTime(new Date()); 
 	   orderList.add(order);
 	   
 	   PurchaseDetail order1 = new PurchaseDetail();
 	   order1.setOrderId("20200102"); 
 	   order1.setProductName("硬盘");
 	   order1.setCount(1);
 	   order1.setPrice(new BigDecimal("222.02"));
 	   order1.setPurchaseTime(new Date()); 
 	   orderList.add(order1);
 	   
 	  purchaseInfo.setLogininfo(vo);
 	  purchaseInfo.setOrderList(orderList);
 	   return  JSONUtil.toJsonStr(purchaseInfo); 
	}
	//http://localhost:8080/samplereport/reportgroup1
	@GetMapping(value = "/reportgroup1") 
	public void reportgroup1(HttpServletRequest request, HttpServletResponse response) throws IOException {
		  try {   
			  String reportName ="sample8.jasper";
			   response.setContentType("application/pdf; charset=utf-8");  
               response.setDateHeader("Expires", 0);  
			   OutputStream os = response.getOutputStream(); 
	    	   JasperReport jasperReport = (JasperReport)JRLoader.loadObject(resourceLoader.getResource("classpath:/jasper/sample8/"+reportName).getInputStream());
	    	    
	    	   JRBeanCollectionDataSource detailDs = new JRBeanCollectionDataSource(BeanFactory.getAllOrderList()); 
	    	   Map param = new HashMap();
	    	   param.put("month", "一月份");
	    	   JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, param,detailDs);
	    	      
	           JasperExportManager.exportReportToPdfStream(jasperPrint,os);  
	} catch (Exception e) {
		 e.printStackTrace();
	}  
	}
	
	@GetMapping(value = "/reportbarcode") 
	public void reportbarcode(HttpServletRequest request, HttpServletResponse response) throws IOException {
		  try {   
			  String reportName ="sample9.jasper";
			   response.setContentType("application/pdf; charset=utf-8");  
               response.setDateHeader("Expires", 0);  
			   OutputStream os = response.getOutputStream(); 
	    	   JasperReport jasperReport = (JasperReport)JRLoader.loadObject(resourceLoader.getResource("classpath:/jasper/sample9/"+reportName).getInputStream());
	    	    
	    	   String imgPath = resourceLoader.getResource("classpath:/jasper/").getURL().toString(); 
	    	   
	    	   JRBeanCollectionDataSource detailDs = new JRBeanCollectionDataSource(BeanFactory.getAllOrderList()); 
	    	   Map param = new HashMap();
	    	   param.put("code", "一月份消费记录");
	    	   param.put("imgPath", imgPath+"myimage.jpg");
	    	   JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, param,detailDs);
	    	      
	           JasperExportManager.exportReportToPdfStream(jasperPrint,os);  
	} catch (Exception e) {
		 e.printStackTrace();
	}  
	}
	
	@GetMapping(value = "/reportstat1") 
	public void reportstat1(HttpServletRequest request, HttpServletResponse response) throws IOException {
		  try {   
			  String reportName ="sample10.jasper";
			   response.setContentType("application/pdf; charset=utf-8");  
               response.setDateHeader("Expires", 0);  
			   OutputStream os = response.getOutputStream(); 
	    	   JasperReport jasperReport = (JasperReport)JRLoader.loadObject(resourceLoader.getResource("classpath:/jasper/sample10/"+reportName).getInputStream());
	    	     
	    	   HashMap<String, Object> hashMap = new HashMap<>(); 
	    	   hashMap.put("purchaseList", BeanFactory.getUserPurchaseStat()); 
	    	   JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, hashMap,new JREmptyDataSource());
	    	      
	           JasperExportManager.exportReportToPdfStream(jasperPrint,os);  
	} catch (Exception e) {
		 e.printStackTrace();
	}
	}
	
	@GetMapping(value = "/reportchart1") 
	public void reportchart(HttpServletRequest request, HttpServletResponse response) throws IOException {
		  try {   
			  String reportName ="sample14.jasper";
			   response.setContentType("application/pdf; charset=utf-8");  
               response.setDateHeader("Expires", 0);  
			   OutputStream os = response.getOutputStream(); 
	    	   JasperReport jasperReport = (JasperReport)JRLoader.loadObject(resourceLoader.getResource("classpath:/jasper/sample14/"+reportName).getInputStream());
	    	     
	    	   HashMap<String, Object> hashMap = new HashMap<>(); 
	    	   hashMap.put("purchaseList", BeanFactory.getChartList()); 
	    	   JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, hashMap,new JREmptyDataSource());
	    	      
	           JasperExportManager.exportReportToPdfStream(jasperPrint,os);  
	} catch (Exception e) {
		 e.printStackTrace();
	}
	}
	
	//动态报表http://localhost:8080/samplereport/reportdyns
		@GetMapping(value = "/reportdyns") 
		public void reportdyns(HttpServletRequest request, HttpServletResponse response) throws IOException {
			  try {   
				  String reportName ="sample15.jrxml";
				   response.setContentType("application/pdf; charset=utf-8");  
	               response.setDateHeader("Expires", 0);  
				   OutputStream os = response.getOutputStream(); 
		    	      
		    	    try {  
		    	      // 从资源文件中读取报表    
		    	      JasperDesign jasperDesign = (JasperDesign) JRXmlLoader.load(resourceLoader.getResource("classpath:/jasper/sample15/"+reportName).getInputStream());  
		    	      JRDesignBand headband = (JRDesignBand)jasperDesign.getColumnHeader();
		    	     
		    	      JRDesignBand detailband = (JRDesignBand)jasperDesign.getDetailSection().getBands()[0];
		    	       
		    	      int startX=200;
		    	      Map<String,String> parentHeadMap = BeanFactory.getParentHead();
		    	      for(int i =0;i<parentHeadMap.size();i++) {
		    	    	  JRDesignStaticText staticText = new JRDesignStaticText();  
			              staticText.setWidth(100);  
			              staticText.setY(0);  
			              staticText.setX(startX);  
			              staticText.setHeight(20);  
			              staticText.setText(parentHeadMap.get(i+""));   
			              staticText.setFontName("华文宋体");
			              startX += 100;  
			              JRDesignElementGroup elemGrp = new JRDesignElementGroup();
			              elemGrp.addElement(staticText); 
			              headband.addElementGroup(elemGrp);
		    	      }  
		    	      	    	      
		    	      startX=200;
		    	      for(int i=1;i<=parentHeadMap.size();i++) {
		    	    	  // 定义报表字段  
		    	    	  JRDesignField field = new JRDesignField();  
			    	      field.setName("totalPrice" + i);  
			    	      field.setValueClass(java.lang.String.class);  
			    	      jasperDesign.addField(field); 
			    	        
			    	      //设置报表模板动态字段属性
		    	    	  JRDesignTextField textField = new JRDesignTextField();  
			    	      textField.setStretchWithOverflow(true);  
			    	      textField.setX(startX);  
			    	      textField.setY(10);  
			    	      textField.setWidth(100);  
			    	      startX += 100;   
			    	      textField.setHeight(20);   
			    	      textField.setBlankWhenNull(true); 
			    	      
			    	      JRDesignExpression expression = new JRDesignExpression();  
			    	      expression.setValueClass(java.lang.String.class);  
			    	      expression.setText("$F{totalPrice" + i + "}");  
			    	      textField.setExpression(expression);   
			    	      detailband.addElement(textField);
		    	      } 
		    	   
		    	     // 编译报表  
		    	      JasperReport jasperReport = JasperCompileManager.compileReport(jasperDesign);  
		    	      JRDataSource dataSource = new JRBeanCollectionDataSource(BeanFactory.getPurchaseStatByProductType()); 
		    	      JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, null,dataSource); 
		    	      //展现报表
		              JasperExportManager.exportReportToPdfStream(jasperPrint,os);   
		                
		    	    }catch(Exception e) {
		    	    	e.printStackTrace();
		    	    } 
		    	 
		} catch (Exception e) {
			 e.printStackTrace();
		}
		}
		
}
